package com.partsoft.dits;

import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Array;

import org.apache.commons.io.IOUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * 抽象的消息字节码批处理
 */
public abstract class AbstractMessageByteBatchProcessor {

	public void process(DataIntegrateBatch batch) {
		validateBatch(batch);
		byte []bytes = null;
		try {
			if (batch.getInputParameter().getClass().isArray()) {
				Assert.isAssignable(Byte.class, Array.get(batch.getInputParameter(), 0).getClass(), "参数必须为字节数组类型。");
				bytes = (byte[]) batch.getInputParameter();
			} else if (ClassUtils.isAssignableValue(InputStream.class, batch.getInputParameter())) {
				InputStream ios = (InputStream) batch.getInputParameter();
				bytes = IOUtils.toByteArray(ios);
			} else if (ClassUtils.isAssignableValue(Reader.class, batch.getInputParameter())) {
				Reader rdr = (Reader) batch.getInputParameter();
				bytes = IOUtils.toByteArray(rdr);
			} else if (ClassUtils.isAssignableValue(String.class, batch.getInputParameter())) {
				bytes = ((String)batch.getInputParameter()).getBytes("utf-8");
			} else {
				throw new IllegalArgumentException(String.format("处理参数不受支持(仅支持InputStream、Reader、String、byte[]、Byte[])。"));
			}
		} catch (Throwable e) {
			batch.setException(new IllegalArgumentException(String.format("传入的处理参数错误：%s", e.getMessage()), e));
			return;
		}
		try {
			batch.setResult(doProcess(batch.getDataDescriptor(), bytes, batch.getAccepter()));
		} catch (Throwable e) {
			batch.setException(e);
		}
	}
	
	protected abstract Object doProcess(DataEdgeDescriptor dataDescriptor, byte[] bytes, DescriptorAccepter<EdgeDescriptor> accepter);
	
	protected void validateBatch(DataIntegrateBatch batch)  {
		Assert.notNull(batch);
		Assert.notNull(batch.getDataDescriptor());
		Assert.isTrue(!batch.isProcessed(), "已经被处理。");
		Assert.notNull(batch.getInputParameter(), "必须设置输入参数。");
	}

}
